//
//  MapViolation.m
//  carcareIOS
//
//  Created by ileo on 16/8/4.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "MapViolation.h"
#import "LocAnnotationView.h"
#import "CommonUtility.h"


@interface MapViolation () <MAMapViewDelegate>

@property (nonatomic, copy) NSArray<LocAnnotation *> *annotations;

@end

@implementation MapViolation

-(void)setVioModels:(NSArray<VioModel *> *)vioModels{
    _vioModels = [vioModels copy];
    
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:vioModels.count];
    [vioModels enumerateObjectsUsingBlock:^(VioModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LocAnnotation *annotation = [[LocAnnotation alloc] initWithCoordinate:obj.coordinate];
        annotation.tag = idx;
        [tmp addObject:annotation];
    }];
    
    self.annotations = [tmp copy];
    CGFloat gap = 50;
    [self.mapView setVisibleMapRect:[CommonUtility minMapRectForAnnotations:tmp] edgePadding:UIEdgeInsetsMake(gap, gap, gap, gap) animated:NO];
}


-(void)showVioMap{
    [self.mapView addAnnotations:self.annotations];
}

-(MAMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
        _mapView.delegate = self;
        _mapView.zoomLevel = 15.5;
    }
    return _mapView;
}

-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{

    if ([annotation isKindOfClass:[LocAnnotation class]]) {
        LocAnnotation *ann = (LocAnnotation *)annotation;
        LocAnnotationView *annotationView = [[LocAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"carAnnotation"];
        BOOL isChoice = ann.tag == self.ChoiceIndex;
        __weak __typeof(self) wself = self;
        annotationView.image = isChoice ? ImageNamed(@"v_map_warn_big") : ImageNamed(@"v_map_warn_small");
        annotationView.Select = ^(){
            wself.ChoiceIndex = ann.tag;
            if (wself.Select) {
                wself.Select(wself.vioModels[ann.tag]);
            }
            [wself.mapView removeAnnotations:wself.annotations];
            [wself showVioMap];
            [wself.mapView setCenterCoordinate:ann.coordinate animated:YES];
            [wself.mapView setZoomLevel:15 atPivot:[wself.mapView convertCoordinate:ann.coordinate toPointToView:wself.mapView] animated:YES];
        };

        annotationView.annotation = annotation;
        annotationView.canShowCallout = NO;
        return annotationView;
    }
    return nil;
}

@end
